import React, { useEffect, useState } from 'react';
import { Empty } from 'antd';
import {
  Chart,
  registerShape,
  Geom,
  Legend,
  Axis,
  Tooltip,
  Interval,
  Interaction,
  Coordinate,
  Annotation,
} from 'bizcharts';
import _ from 'lodash';

const sliceNumber = 0.01; // 自定义 other 的图形，增加两条线
registerShape('interval', 'sliceShape', {
  draw(cfg, container) {
    const points = cfg.points;
    let path = [];
    path.push(['M', points[0].x, points[0].y]);
    path.push(['L', points[1].x, points[1].y - sliceNumber]);
    path.push(['L', points[2].x, points[2].y - sliceNumber]);
    path.push(['L', points[3].x, points[3].y]);
    path.push('Z');
    path = this.parsePath(path);
    return container.addShape('path', {
      attrs: {
        fill: cfg.color,
        path: path,
      },
    });
  },
});

export default ({ chartData }) => {
  const [sum, setSum] = useState();
  useEffect(() => {
    if (chartData?.length) {
      setSum(_.sumBy(chartData, 'y'));
    }
  }, [chartData]);
  return chartData ? (
    <Chart data={chartData} autoFit>
      <Coordinate type="theta" radius={0.8} innerRadius={0.75} />
      <Legend visible={false} />
      <Axis visible={false} />
      <Tooltip showTitle={false} />
      <Interval
        adjust="stack"
        position="y"
        color="x"
        shape="sliceShape"
        label={[
          'y',
          { offset: 40 },
          {
            content: (data) => {
              return `${data.x}:${data.y}`;
            },
            offset: 22,
          },
        ]}
      />
      <Annotation.Text
        position={['50%', '40%']}
        content="总计"
        style={{
          lineHeight: '100px',
          fontSize: '18',
          fill: '#262626',
          textAlign: 'center',
        }}
      />
      <Annotation.Text
        position={['50%', '60%']}
        content={`${sum}次`}
        style={{
          lineHeight: '100px',
          fontSize: '18',
          fill: '#262626',
          textAlign: 'center',
        }}
      />
    </Chart>
  ) : (
    <Empty />
  );
};
